/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-27 11:56:42
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-05-23 15:52:32
 * @FilePath: /vue3-admin/src/views/system/RolesManage/components/EditView/useForm.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ref, type Ref, watch } from 'vue';
import { useRole, RoleParam } from '@/service/biz/useRole';
import { useRules } from '@/service/useRules';
import type { FormInstance } from 'element-plus';
import { treeToArray } from '@/utils/array';

export const useForm = (
    formRef: Ref<FormInstance | undefined>,
    idRef: Ref<number | undefined> | undefined,
    modelValueRef: Ref<boolean>,
    afterSubmit: () => void
) => {
    const dialogTitle = ref('新增');

    const { updateRole, getDetail, detailLoading, detail, updateLoading } =
        useRole();

    const formModel = ref(new RoleParam());

    const { requiredRule } = useRules();

    const rules = {
        name: [...requiredRule],
        menuIds: [...requiredRule],
        description: [...requiredRule]
    };

    const handleSubmit = () => {
        formRef.value?.validate(async (isValid) => {
            if (isValid) {
                await updateRole(formModel.value);
                afterSubmit();
            }
        });
    };

    const handleEdit = async (id?: number) => {
        formModel.value = new RoleParam();
        if (id) {
            dialogTitle.value = '修改';
            await getDetail(id);
            formModel.value.id = idRef && idRef.value;
            formModel.value.name = detail.value?.name || '';
            formModel.value.description = detail.value?.description || '';
            if (detail.value?.menuTree) {
                formModel.value.menuIds = treeToArray(
                    undefined,
                    detail.value.menuTree
                ).map((item) => item.id);
            }
        } else {
            dialogTitle.value = '修改';
        }
    };

    watch(
        () => modelValueRef.value,
        (newVal) => {
            if (newVal) {
                formRef.value?.clearValidate();
                handleEdit(idRef && idRef.value);
            }
        },
        {
            immediate: true
        }
    );

    return {
        dialogTitle,
        formModel,
        detailLoading,
        updateLoading,
        handleSubmit,
        handleEdit,
        rules
    };
};
